// pages/user/user.js
import { Base } from '../../utils/base.js'
import { Login } from './signin-model.js'
import { hex_md5 } from '../../utils/md5.js'
const app = getApp();
let base = new Base();
let login = new Login();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: null,
        disabled: false,
        yzm: '',
        phone: '',
        password: '',
        timer: 59,
        isShow: true,
        nowType: 'yzm',
        isAuthor: false,
        isHasUserInfo: false,
        inviteCode: ""
    },
    onLoad(options) {
        console.log("sign-options-------", options);
        let sessionId = wx.getStorageSync("sessionId");
        // let inviteCode = wx.getStorageSync("inviteCode");
        // console.log("inviteCode=================",inviteCode);
        //获取分享人的手机号
        // if (inviteCode && inviteCode!=""){
        //   this.setData({
        //     // inviteCode,
        //     'pageType':'share'
        //   })
        // }

        console.log('sessionId', sessionId)
        //替换页面的分享，需要options传path参数
        if (options) {
            this.setData({
                options
            })
        }

    },
    getSetting(cb) {
        let that = this
        wx.getSetting({
            success(res) {
                console.log(res, 'res')
                let authSetting = res.authSetting
                if (Object.keys(authSetting).indexOf('scope.userInfo') >= 0 && authSetting['scope.userInfo']) {
                    cb && cb()

                } else {
                    wx.setNavigationBarTitle({
                        title: '登录'
                    })
                    wx.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#000000',
                    })
                    that.setData({
                        isShow: true
                    })
                    // app.getUserSetting(()=>{
                    //     wx.switchTab({
                    //         url: '/pages/index/index',
                    //     })
                    // })
                }
            }
        })
    },
    onShow() {
        // wx.getSetting({})
    },
    //   切换登陆方式
    changType(e) {
        let val = e.currentTarget.dataset.type
        this.setData({
            nowType: val
        })

    },
    //  设置手机号的值
    setPhone(e) {
        let val = e.detail.value
        this.setData({
            phone: val
        })
    },
    //   检查手机号
    checkPhone(e) {
        console.log(e)
        let val = e.detail.value

        if (val == '') {
            wx.showToast({
                icon: 'none',
                title: '请输入手机号'
            })
        } else if (!/^1[345678]\d{9}$/g.test(val)) {
            wx.showToast({
                icon: 'none',
                title: '请输入正确的手机号'
            })
        }
    },
    //   获取用户信息
    getUserInfo(e) {
        console.log(e)

        this.setData({
            isAuthor: false
        })
        if (e.detail.errMsg != 'getUserInfo:ok') {
            console.log('fail')
            app.showTips(() => {
                wx.hideLoading()
                //分享进入跳转到分享页面
                this.limitLogin(this);

            })
        } else {
            console.log('app.globalData.isLogin', app.globalData.isLogin)
            wx.showLoading({
                title: '加载中...',
            })

            app._loginUser(e.detail, () => {
                wx.hideLoading()

                this.limitLogin(this);
            })


        }
    },
    checkPhoneGetYzm(cb) {
        let { phone } = this.data
        if (phone == '') {
            wx.showToast({
                icon: 'none',
                title: '请输入手机号'
            })
        } else if (!/^1[345678]\d{9}$/g.test(phone)) {
            wx.showToast({
                icon: 'none',
                title: '请输入正确的手机号'
            })
        } else {
            cb && cb()
        }
    },
    // 发送验证码
    getYzm() {
        console.log(this.data.phone)
        let { phone } = this.data
        let timer = null
        let time = 59
        console.log(/^1[345678]\d{9}$/g.test(phone), phone.length)
        console.log('send')
        if (phone == '') {
            wx.showToast({
                icon: 'none',
                title: '请输入手机号'
            })
        } else if (!/^1[345678]\d{9}$/g.test(phone)) {
            wx.showToast({
                icon: 'none',
                title: '请输入正确的手机号'
            })
        } else {
            console.log('phone', phone)
            wx.showLoading({
                title: '加载中...',
            })
            login.sendVerifyCode({ verifyPhone: phone }, res => {
                wx.hideLoading()
                if (!res.status) {
                    wx.showToast({
                        icon: 'none',
                        title: res.message
                    })
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '发送验证码成功，请您查收'
                    })
                    this.setData({
                        disabled: true
                    })
                    timer = setInterval(() => {
                        if (time == 0) {
                            clearInterval(timer)
                            this.setData({
                                disabled: false,
                                timer: 59
                            })
                        }
                        this.setData({
                            timer: time
                        })
                        time--
                    }, 1000)
                }
            })
        }
    },
    //   登录
    onLogin: function (e) {

        let that = this;
        let { name, yzm, password } = e.detail.value;
        let { nowType } = this.data
        let params
        if (name == "") {
            wx.showToast({
                icon: 'none',
                title: '手机号不能为空'
            })
            return;
        }
        if (!/^1[345678]\d{9}$/g.test(name)) {
            wx.showToast({
                icon: 'none',
                title: '请输入正确的手机号'
            })
            return;
        }
        if (nowType == 'yzm') {
            if (yzm.trim() == "") {
                wx.showToast({
                    icon: 'none',
                    title: '验证码不能为空'
                })
                return;
            }
            if (!/\d{6}/g.test(yzm)) {
                wx.showToast({
                    icon: 'none',
                    title: '验证码为6位的数字'
                })
                return;
            }
            params = {
                "verifyPhone": name,
                "verifyCode": yzm
            }
            wx.showLoading({
                title: '加载中...',
            })
            login.bindPhone(params, res => {
                this.handleLoginResult(res, name)
            });
        } else {
            if (password.trim() == "") {
                wx.showToast({
                    icon: 'none',
                    title: '密码不能为空'
                })
                return;
            }
            params = {
                "verifyPhone": name,
                "password": hex_md5(password),
            }
            wx.showLoading({
                title: '加载中...',
            })
            login.loginByPwd(params, res => {
                this.handleLoginResult(res, name)
            });
        }

        console.log(params)


    },
    //   点击登录成功处理结果
    handleLoginResult(res, name) {
        console.log(res);
        wx.hideLoading()
        if (res.status) {
            //   wx.setStorageSync('sessionId', res.data.sessionId)
            wx.setStorageSync('phone', name)

            //   this.setData({
            //       isAuthor: true
            //   })
            this.limitLogin(this)
        } else {
            wx.showToast({
                icon: 'none',
                title: res.message
            })
        }
    },
    onShow() {

        console.log("onShow-----------------------");

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    limitLogin: function (that) {

        //分享进入跳转到分享页面
        console.log('type--------------', that.data.pageType);

        let path = that.data.options.path;
        console.log('path===================', path);

        if (path) {
            wx.removeStorageSync('inviteCode');
            let options = that.data.options;

            let params = "";
            console.log("options--------------------", options)
            for (var variable in options) {   //variable 为属性名
                console.log("variable----------", variable);
                if (variable != 'path') {
                    params += variable + "=" + options[variable] + '&'
                }
            }
            console.log("跳转--------", path + '?' + params, path)
            if (path == "/pages/user/user" || path == "/pages/cart/cart") {
                wx.switchTab({
                    url: params == '' ? path : path + '?' + params,
                })
            } else {
                wx.redirectTo({
                    url: params == '' ? path : path + '?' + params,
                })
            }

        } else if (!that.data.pageType) {
            wx.switchTab({
                url: '/pages/index/index',
            })
        } else {
            wx.removeStorageSync('inviteCode');
            // wx.setStorageSync('pageType', 'share') //分享进入页面标识
            wx.navigateBack();
        }
    }

})